const db = require('../config/database');

class UserLog {
  static db = db;
  static async getAll({ tool_name, name, start, end, page = 1, pageSize = 10 } = {}) {
    let sql = `
      SELECT 
        u.no, u.user_name AS name, u.create_at AS start_time, u.ip, u.computer_name, u.diff_time AS use_time,
        u.tool_id, t.name AS tool_name
      FROM user_log u
      LEFT JOIN lib_tool t ON u.tool_id = t.uuid
      WHERE 1=1
    `;
    const params = [];
    if (tool_name) {
      sql += ' AND t.name LIKE ?';
      params.push(`%${tool_name}%`);
    }
    if (name) {
      sql += ' AND u.user_name LIKE ?';
      params.push(`%${name}%`);
    }
    if (start) {
      sql += ' AND u.create_at >= ?';
      params.push(start);
    }
    if (end) {
      sql += ' AND u.create_at <= ?';
      params.push(end);
    }
    sql += ' ORDER BY u.no';
    // 分页
    const offset = (parseInt(page) - 1) * parseInt(pageSize);
    sql += ' LIMIT ?, ?';
    params.push(offset, parseInt(pageSize));
    const [rows] = await db.query(sql, params);
    // 查询总数
    let countSql = `SELECT COUNT(*) as total FROM user_log u LEFT JOIN lib_tool t ON u.tool_id = t.uuid WHERE 1=1`;
    const countParams = [];
    if (tool_name) {
      countSql += ' AND t.name LIKE ?';
      countParams.push(`%${tool_name}%`);
    }
    if (name) {
      countSql += ' AND u.user_name LIKE ?';
      countParams.push(`%${name}%`);
    }
    if (start) {
      countSql += ' AND u.create_at >= ?';
      countParams.push(start);
    }
    if (end) {
      countSql += ' AND u.create_at <= ?';
      countParams.push(end);
    }
    const [countRows] = await db.query(countSql, countParams);
    return { rows, total: countRows[0].total };
  }
  static async create(data) {
    const { name, tool_id, start_time, ip, computer_name, use_time } = data;
    const [result] = await db.query(
      'INSERT INTO user_log (user_name, tool_id, create_at, ip, computer_name, diff_time) VALUES (?, ?, ?, ?, ?, ?)',
      [name, tool_id, start_time, ip, computer_name, use_time]
    );
    return result.insertId;
  }
  static async update(no, data) {
    const { name, tool_id, start_time, ip, computer_name, use_time } = data;
    const [result] = await db.query(
      'UPDATE user_log SET user_name=?, tool_id=?, create_at=?, ip=?, computer_name=?, diff_time=? WHERE no=?',
      [name, tool_id, start_time, ip, computer_name, use_time, no]
    );
    return result.affectedRows > 0;
  }
  static async delete(no) {
    const [result] = await db.query('DELETE FROM user_log WHERE no=?', [no]);
    return result.affectedRows > 0;
  }
}

UserLog.db = db;

module.exports = UserLog;